package com.uzhie.util;

import com.alibaba.fastjson.JSONArray;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 *
 * 远程目录请求回调缓存,用以存储当前线程队列及消息返回结果集,当获取到对应线程后,存储返回集合,并释放线程等待
 * Created by lilongfei on 2018/8/3.
 */
public class ConcurrentCollection {

    ConcurrentMap<String,JSONArray> result;
    ConcurrentMap<String,Thread> threadIds;

    private static ConcurrentCollection concurrentCollection;

    private ConcurrentCollection(){
        this.result = new ConcurrentHashMap<>();
        this.threadIds = new ConcurrentHashMap<>();
    }

    public static  ConcurrentCollection getInstance(){
        if (concurrentCollection ==null)
            synchronized (ConcurrentCollection.class) {
                if (concurrentCollection == null)
                    concurrentCollection = new ConcurrentCollection();
            }
        return concurrentCollection;
    }

    public void setThread(String key, Thread value){
        threadIds.put(key,value);
    }

    public Thread getThread(String key){
        return threadIds.get(key);
    }

    public int getThreadSize(){
        if (threadIds!=null) return threadIds.size();
        return 0;
    }

    public void setResult(String key,JSONArray value){
        result.put(key,value);
    }

    public JSONArray getResult(String key){
        return result.get(key);
    }

    public void removeThread(String key){
        threadIds.remove(key);
    }

    public void removeResult(String key){
        result.remove(key);
    }

    public void removeAll(String key){
        result.remove(key);
        threadIds.remove(key);
    }

    public boolean containsKey(String key){
        if (result.containsKey(key) && threadIds.containsKey(key)) return true;
        return false;
    }
}
